# Model_Data_gles

# Creates the vignett speciifc data from the gles dataset



# Switch Function
party.num <- function(party="ovp",vote=FALSE){

  # given name return
  # IF vote=FALSE letter for party to get columns
  # vote=TRUE and number that indicates vote choice
  
  num <- switch(party
         ,cdu = ifelse(vote==TRUE,1,"a")
         ,spd = ifelse(vote==TRUE,4,"c")
         ,fdp = ifelse(vote==TRUE,5,"d")
         ,gruene = ifelse(vote==TRUE,6,"e")
         ,linke = ifelse(vote==TRUE,7,"f")
         ,party)

  return(num)
  }


# Creat vignett specific dataset
create.data <- function(
                        data=gles
                        ,parties=c("cdu","gruene"), vignette="a"
                        ,coal="f"
                        ,drop.na=FALSE
    ){

  coal.vig <- paste("wahlvig_", vignette,sep="")

  # Create Dependent Variable
  # get vote variable
  vote <- sapply(parties,party.num,vote=TRUE)

  if(drop.na==TRUE) {
    
    data$wahl_b[data$wahl_b>90] <- NA
    sel <- which(names(data)==coal.vig)
    data[,sel] <- ifelse(data[,sel]>90,NA,data[,sel])
    
  }
  
  # Create Options for normal Vote
  data$a1[!(data$wahl_b %in% vote)  & !is.na(data$wahl_b)] <- length(vote)+1
  for(i in 1:length(vote)){
    data$a1[data$wahl_b == vote[i]] <- i
  }

  # Create Choice second Vote
  data$a2[!(data[coal.vig] %in% vote)  & !is.na(data[coal.vig]) ] <- length(vote)+1
  for(i in 1:length(vote)){
    data$a2[data[coal.vig] == vote[i]] <- i
  }

  table(data$a1  ,data$a2)

  data$Y <- NULL
  K <- 1

  for(j in sort(na.omit(unique(data$a1))) ){
    for(k in sort(na.omit(unique(data$a2))) ){
  data$Y[data$a1==j & data$a2==k] <- K
  K <- K +1
  }}


  # Creat party ID dummies
  library(dummies)
  d.pid <- dummy(data$pid)
  colnames(d.pid) <- paste("pid",c(1,4,5,6,7,8,84,"NA"),sep="")
  d.pid <- d.pid[,paste("pid",vote,sep="")]
  
  # get Controls
  sel.con <- grep("con_",names(data))

  names(data)
  # party codes
  party <- sapply(parties,party.num)
 
  # Rating
  rat.c <- paste("ratcoal_",coal[1],sep="")
  rat.p <- paste("rat_",party,sep="")

  # Position
  pos.p <- paste("lr_",party,sep="")
  Up <- - (data$lrs - data[pos.p])^2

  
  dta <- cbind(data$Y,Up,data[rat.p],data[rat.c],data$a1,data[,grep("I",names(data))],d.pid,data[,sel.con])
  


  dta <- na.omit(dta)
  return(dta)
  
  
}
